package cn.maihe.elg.operation.centers.hymake.handler.service;

import cn.maihe.elg.operation.centers.hymake.config.HyMakeInfoConfig;
import cn.maihe.elg.operation.centers.hymake.dto.handler.vo.xm.XMBaseRespDTO;
import cn.maihe.elg.operation.centers.hymake.dto.handler.vo.xm.XMCheckGuaranteeReqDTO;
import cn.maihe.elg.operation.centers.hymake.dto.handler.vo.xm.XMPolicyNoDTO;
import cn.maihe.elg.operation.centers.hymake.enums.HyMakeRespCodeEnum;
import cn.maihe.elg.operation.centers.hymake.enums.XMRespCodeEnum;
import cn.maihe.elg.operation.centers.hymake.exception.HyMakeException;
import cn.maihe.elg.operation.centers.hymake.handler.HyMakeCenterTradeService;
import cn.maihe.elg.operation.centers.supports.CenterTradeContext;
import cn.maihe.elg.operation.centers.supports.annotation.CenterTradeService;
import cn.maihe.elg.operation.model.bo.BidderCustomerBO;
import cn.maihe.elg.operation.model.enums.BidCustomerStatus;
import cn.maihe.elg.operation.model.enums.CenterNoEnum;
import cn.maihe.elg.operation.model.enums.CenterProviderEnum;
import cn.maihe.elg.operation.model.enums.IDType;
import cn.maihe.elg.operation.model.enums.InstitutionOrgCodeEnum;
import cn.maihe.elg.operation.model.enums.TradeType;
import cn.maihe.elg.operation.model.enums.UserStatusEnum;
import cn.maihe.elg.operation.model.enums.UserType;
import cn.maihe.elg.operation.repository.entity.BidCustomerDO;
import cn.maihe.elg.operation.repository.entity.GuaranteeInstitutionDO;
import cn.maihe.elg.operation.repository.entity.UserDO;
import cn.maihe.elg.operation.service.business.BidCustomerService;
import cn.maihe.elg.operation.service.order.AcceptOrderInfoService;
import cn.maihe.elg.operation.service.system.impl.OrganizationServiceImpl;
import cn.maihe.elg.operation.supports.system.ElgResourceService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description 保函验真申请
 * @Author caixh
 * @Date 2022/3/30.
 */
@CenterTradeService(
        provider = CenterProviderEnum.XIANMEN,
        centerNo = CenterNoEnum.XIAMEN,
        tradeType = TradeType.checkQualification,
        reqClass = XMCheckGuaranteeReqDTO.class,
        respClass = XMBaseRespDTO.class
)
@Slf4j
public class XMCheckQualificationService extends HyMakeCenterTradeService<XMCheckGuaranteeReqDTO, XMBaseRespDTO> {

    @Value("${cn.maihe.elg.default-service-phone:15105003959}")
    private String defaultServicePhone;

    @Resource
    AcceptOrderInfoService acceptOrderInfoService;


    @Resource
    BidCustomerService bidCustomerService;
    @Resource
    OrganizationServiceImpl organizationService;
    @Resource
    private ElgResourceService elgResourceService;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    // 定义一个清晰的Redis Key前缀
    public static final String PENDING_LOGIN_KEY_PREFIX = "login:pending:token:";

    public XMCheckQualificationService(HyMakeInfoConfig centerInfosConfig) {
        super(centerInfosConfig);
    }


    /**
     * 厦门：查询资格校验
     *
     * @param context
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public XMBaseRespDTO processService(CenterTradeContext<XMCheckGuaranteeReqDTO, XMBaseRespDTO> context) {

        XMCheckGuaranteeReqDTO req = context.getReq();
        Long centerId = context.getCenterId();
        Long orgId = context.getOrgId();

        XMPolicyNoDTO item = context.getReq().getPolicyList().get(0);
        BidderCustomerBO bidderCustomerBO = parseBidderCheckInfo(context);
        bidderCustomerBO = bidCustomerService.saveBidderCustomerBO(bidderCustomerBO);
        String bidderLoginUrl = elgResourceService.buildElgFrontUrl("/#/bidderLogin");

        if (BidCustomerStatus.REGIST.getStatus() == bidderCustomerBO.getBidCustomer().getStatus()
                || BidCustomerStatus.AUDIT_FAIL.getStatus() == bidderCustomerBO.getBidCustomer().getStatus()) {
            String completeInfoLoginUrl = elgResourceService.buildElgFrontUrl(String.format("/#/freeLogin?bidCustomerId=%s",bidderCustomerBO.getBidCustomer().getId()));
            String hint = "企业没有认证！";
            String link = new StringBuilder().append("<a href=\"")
                    .append(completeInfoLoginUrl)
                    .append("\" style=\"color: blue;font-size: 18px;\" target=\"_blank\">")
                    .append("去认证")
                    .append("</a>").toString();

            return XMBaseRespDTO.builder()
                    .success(false)
                    .errorCode(XMRespCodeEnum.FAILURE.getRespCode())
                    .errorDesc(hint+link)
                    .build();
        } else if (BidCustomerStatus.NORMAL.getStatus() != bidderCustomerBO.getBidCustomer().getStatus()) {
            String buildError = new StringBuilder()
                    .append("投标人信息状态异常，请联系客服人员处理，客服电话：")
                    .append(defaultServicePhone)
                    .toString();
            return XMBaseRespDTO.builder()
                    .success(false)
                    .errorCode(XMRespCodeEnum.FAILURE.getRespCode())
                    .errorDesc(buildError)
                    .build();
        }

        //保存&更新投标客户
//        BidCustomerDO curBidCustomer = bidCustomerService.saveOrUpdateBidCustomer(bo.getBidCustomer());
//        bo.setBidCustomer(curBidCustomer);
//
//        //保存或更新投标客户登录账号：登录账号：社会信用代码 密码默认123456
//        bo.getUserDO().setOrgId(curBidCustomer.getId());
//        userService.saveOrUpdateBidUser(bo.getUserDO());
        // Todo 目前不确定该字段应该从哪个表获取
        String appId = item.getAppId();

//        // 1. 根据投标人信息与工程担保保证人信息查询
//        String bidderName = item.getBidderName();
//        String bidderOrgCode = item.getBidderOrgCode();
//
//        String guarantorName = item.getGuarantorName();
//        String guarantorCreditCode = item.getGuarantorCreditCode();
//
//
//        BidCustomerDO bidCustomerDO = bidCustomerService.selectOne(BidCustomerDOCondition.builder().andBidderNameEq(bidderName).andBidderCreditCodeEq(bidderOrgCode).build());
//        if (bidCustomerDO == null) {
//            return XMBaseRespDTO.builder()
//                    .success(false)
//                    .errorCode(HyMakeCheckResultEnum.FAILURE.getCheckResult())
//                    .errorDesc("投标人信息不存在")
//                    .build();
//        }
//
//        OrganizationDO organizationDO = organizationService.selectOne(OrganizationDOCondition.builder().andFullNameEq(guarantorName).andCreditCodeEq(guarantorCreditCode).build());
//
//        if (organizationDO == null) {
//            return XMBaseRespDTO.builder()
//                    .success(false)
//                    .errorCode(HyMakeCheckResultEnum.FAILURE.getCheckResult())
//                    .errorDesc("工程担保保证人不存在")
//                    .build();
//
////                                return HyMakeBondCheckItemDTO.builder().build();
//        }
//
//        AcceptOrderInfoDO orderInfo = acceptOrderInfoService.selectOne(AcceptOrderInfoDOCondition.builder().andBidCustomerIdEq(bidCustomerDO.getId()).andOrgIdEq(organizationDO.getId()).build());
//        if (orderInfo == null) {
//            return XMBaseRespDTO.builder()
//                    .success(false)
//                    .errorCode(HyMakeCheckResultEnum.FAILURE.getCheckResult())
//                    .errorDesc("保函信息不存在")
//                    .build();
//        }
//        if (orderInfo.getStatus() != AcceptOrderStatus.HAS_OUT_GUARANTEE.getStatus() && orderInfo.getStatus() != AcceptOrderStatus.REVOKE_FAIL.getStatus()) {
//            return XMBaseRespDTO.builder()
//                    .success(false)
//                    .errorCode(HyMakeCheckResultEnum.FAILURE.getCheckResult())
//                    .errorDesc("保函无效")
//                    .build();
//        }

        return XMBaseRespDTO.builder()
                .success(true)
                .build();
    }

    /**
     * 解析 受理的清单信息
     */
    private BidderCustomerBO parseBidderCheckInfo(CenterTradeContext<XMCheckGuaranteeReqDTO, XMBaseRespDTO> context) {
        XMPolicyNoDTO item = context.getReq().getPolicyList().get(0);
        long centerId = context.getCenterId();
        long orgId = context.getOrgId();
        //固定得兴担保直开式
        InstitutionOrgCodeEnum institutionOrgCodeEnum = InstitutionOrgCodeEnum.resolve(context.getOrgCode());
//        InstitutionCode curInstitutionCode = InstitutionCode.deXing;
        GuaranteeInstitutionDO institutionDO = getInstitutionIdByCode(institutionOrgCodeEnum);

        BidCustomerDO bidCustomerDO = this.buildBidCustomerInfo(context.getReq(), centerId, orgId);
        UserDO userDO = this.buildUserInfo(context.getReq(), centerId, orgId);
        BidderCustomerBO bidderCustomerBO = BidderCustomerBO.builder().centerId(centerId).orgId(orgId)
                .bidCustomer(bidCustomerDO).userDO(userDO).build();

        return bidderCustomerBO;
    }

    private BidCustomerDO buildBidCustomerInfo(XMCheckGuaranteeReqDTO req, long centerId, long orgId) {
        // 其他信息通过 企业认证补充页面收集
        XMPolicyNoDTO data = req.getPolicyList().get(0);
//        TbInsuranceSchema insuranceSchema = data.getTbInsuranceSchema();
//        TbMainLiab mainLiab = data.getTbMainLiab();
//        TbProvinceSupply provinceSupply = data.getTbProvinceSupply();

        BidCustomerDO bidCustomer = new BidCustomerDO();
        bidCustomer.setCenterId(centerId);
        bidCustomer.setOrgId(orgId);
        bidCustomer.setBidderName(data.getBidderName());
        bidCustomer.setBidderCreditCode(data.getBidderOrgCode());
        bidCustomer.setBidderContactName(null);
        bidCustomer.setBidderContactTel(null);
        bidCustomer.setBidderContactIdcard(null);
        bidCustomer.setBidderContactIdcardType(IDType.ID_CARD.getType());
        bidCustomer.setBidderEamil(null);
        bidCustomer.setBidderAddress(null);
        bidCustomer.setLegalPersonName(null);
        bidCustomer.setLegalPersonIdcard(null);
        bidCustomer.setLegalPersonIdcardType(IDType.ID_CARD.getType());
        bidCustomer.setLegalPersonTel(null);
        bidCustomer.setEnableAutoApprove(0);
        bidCustomer.setBlacklistFlag(0);
        bidCustomer.setBidderCapital(null);
        bidCustomer.setBidderLegal(null);
        bidCustomer.setBidderBeginDate(null);
        bidCustomer.setBidderEndDate(null);
        bidCustomer.setBidderRegAddress(null);
        bidCustomer.setBidderWebsite(null);
        bidCustomer.setBidderIpcNo(null);
        bidCustomer.setLegalBeginDate(null);
        bidCustomer.setLegalEndDate(null);
        bidCustomer.setLicenseName(null);
        bidCustomer.setLicenseAccount(null);
        bidCustomer.setLicenseLegal(null);
        bidCustomer.setLicenseBank(null);
        bidCustomer.setLicenseCheckNo(null);
        bidCustomer.setLicenseNo(null);
        bidCustomer.setStatus(BidCustomerStatus.REGIST.getStatus());
        bidCustomer.setAuditDesc(null);
        bidCustomer.setFollowId(data.getBidderOrgCode());
        bidCustomer.setBeiandiquCode(null);
        bidCustomer.setBankName(null);
        bidCustomer.setBankCardNum(null);
        bidCustomer.setBankUserName(null);
        bidCustomer.setComTelArea(null);
        bidCustomer.setComTelNum(null);
        bidCustomer.setProvince(null);
        bidCustomer.setCity(null);
        bidCustomer.setDistrict(null);
        bidCustomer.setEnterpriseId(null);
        bidCustomer.setResultQueryTimes(null);

        return bidCustomer;

    }

    private UserDO buildUserInfo(XMCheckGuaranteeReqDTO req, long centerId, long orgId) {
        XMPolicyNoDTO data = req.getPolicyList().get(0);
        return UserDO.builder()
                .umLogin("0")
                .followId(data.getBidderOrgCode())
                .username(data.getBidderOrgCode())
                .mobileNo(null)//改成统一社会信用代码登录
                .name(data.getBidderName())
                .type(UserType.BIDDER.getType())
                .status(UserStatusEnum.NORMAL.name())
                .orgCode("-1")
                .gmtCreate(new Date())
                .gmtModified(new Date())
                .build();
    }

    @Override
    protected Map<String, Object> reorganizeParams(Map<String, Object> context) {

        List<Map<String, Object>> innerParam = new ArrayList<>(1);
        innerParam.add(context);

        Map<String, Object> objectObjectHashMap = new HashMap<>();
        objectObjectHashMap.put("policyList", innerParam);

        return objectObjectHashMap;
    }

    @Override
    protected XMCheckGuaranteeReqDTO buildReq(Map<String, Object> clearParams) {
        try {
            return JSONObject.parseObject(JSONObject.toJSONString(clearParams), this.reqClass);
        } catch (Exception e) {
            throw HyMakeException.of(HyMakeRespCodeEnum.FAILURE, "反序列化异常", e);
        }

    }
}
